﻿namespace instamuz.Application.Controllers
{
    using System.Collections.Generic;
    using System.Web.Mvc;
    using Criterias.Account;
    using Criterias.Post;
    using Domain.Dtos;
    using Domain.Entities;
    using IndyCode.Infrastructure.Domain;
    using NArms.AutoMapper;
    using Services;
    using ViewModels;

    public class IndexController : Controller
    {
        private readonly IContextAccountProvider _contextAccountProvider;
        private readonly IUnitOfWorkFactory _unitOfWorkFactory;
        private readonly IQueryBuilder _queryBuilder;

        public IndexController(IContextAccountProvider contextAccountProvider,
                               IUnitOfWorkFactory unitOfWorkFactory, IQueryBuilder queryBuilder)
        {
            _contextAccountProvider = contextAccountProvider;
            _unitOfWorkFactory = unitOfWorkFactory;
            _queryBuilder = queryBuilder;
        }

        public ActionResult Index(string id)
        {
            using (_unitOfWorkFactory.Create())
            {
                var contextAccount = _contextAccountProvider.GetContextAccount();

                if (id == "feed")
                    return Feed(contextAccount);

                if (string.IsNullOrEmpty(id))
                {
                    if (contextAccount == null)
                        return View("WelcomePage");

                    return Feed(contextAccount);
                }

                var account = _queryBuilder
                    .For<Account>()
                    .With(new FindAccountByLoginCriteria(id));

                if (account == null)
                    return View("AccountNotFound");

                var posts = _queryBuilder
                    .For<IEnumerable<Post>>()
                    .With(new FindPostsForAccountCriteria(account, 0, 20))
                    .MapEachTo<PostDto>();

                var accountModel = new AccountFeedViewModel(contextAccount, account, posts);

                return View("AccountWall", accountModel);
            }
        }

        public ActionResult Feed(Account contextAccount)
        {
            var posts = _queryBuilder
                .For<IEnumerable<Post>>()
                .With(new FindFeedForAccountCriteria(contextAccount))
                .MapEachTo<PostDto>();

            var model = new AccountFeedViewModel(contextAccount, contextAccount, posts);

            return View("AccountWall", model);
        }
    }
}